﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Skynet.WebFoundation.Services.Navigation;
using Skynet.WebFoundation.Services.Session;
using Skynet.BusinessEntities;
using System.ComponentModel;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using System.Xml.Linq;
using Infrastructure.Aspect.Dynamic;

namespace Skynet.WebAdministracion.Views.DesignStartExam
{
    [System.ComponentModel.DataObject]
    public class DesignStartExamPresenter : Infrastructure.Web.Views.Master.MasterPresenter<IDesignStartExamView>
    {
        [Dependency]
        public BusinessLogic.BusinessComponents.IBCCustomers BCCustomers { get; set; }

        [Dependency]
        public BusinessLogic.BusinessComponents.IBCExams BCExams { get; set; }

        [Dependency]
        public BusinessLogic.BusinessComponents.IBCExamQueries BCExamQueries { get; set; }

        [Dependency]
        public INavigationService NavigationService { get; set; }

        [Dependency]
        public ISessionService SessionService { get; set; }

        public override void OnViewInitialized()
        {
            base.OnViewInitialized();
            this.View.Categories = this.BCExamQueries.SearchExamCategories();
            if (this.SessionService.DesignCategoryExamId != null)
            {
                this.View.CategoryId = this.SessionService.DesignCategoryExamId.Value;
            }
            Exam exam = null;
            if (this.SessionService.DesignExamId != null)
            {
                exam = this.BCExamQueries.SearchExams(options: BusinessLogic.BusinessComponents.ExamSearchOptions.GetOne, id: this.SessionService.DesignExamId).SingleOrDefault();                
            }
            else
            {
                exam = new Exam();
                exam.Id = Guid.NewGuid();
                exam.CreatedBy = this.SessionService.CustomerId.Value;
                exam.CategoryExamId = this.View.CategoryId;
                exam.Title = "New Exam";
                exam.MarkAsAdded();
                this.SessionService.DesignExamId = exam.Id;
                this.BCExams.MaintenanceExams(exam);
            }
            this.View.CategoryId = exam.CategoryExamId;
            this.View.ExamTitle = exam.Title;            
        }
        public override void OnViewLoaded()
        {
                  
        }
        private void UpdateExamInformation()
        {

            


            BusinessEntities.Exam exam = null;
            exam = this.BCExamQueries.SearchExams(options: BusinessLogic.BusinessComponents.ExamSearchOptions.GetOne, id: this.SessionService.DesignExamId).SingleOrDefault();
            exam.CategoryExamId = this.View.CategoryId;
            exam.Title = this.View.ExamTitle;
            exam.Summary = this.View.Summary; 
            exam.MarkAsModified();


            var validation = ValidationFactory.CreateValidator<Exam>();
            var results = validation.Validate(exam);

            this.BCExams.MaintenanceExams(exam);
        }

        public void GenerateQuestions()
        {
            UpdateExamInformation();
            this.SessionService.DesignQuestionId = null;
            this.NavigationService.NavigateRoute(Constants.RoutesNames.DesignQuestion);
        }
        

        [DataObjectMethod(DataObjectMethodType.Select, false)]
        public IEnumerable<dynamic> GetQuestions()
        {

            var result = this.BCExamQueries.QueryQuestions(options: BusinessLogic.BusinessComponents.QueryQuestionsOptions.DesignByExamView, ExamId: this.SessionService.DesignExamId);
            if (string.IsNullOrWhiteSpace(result)) return null;  
            var query = (from c in XElement.Parse(result).Elements("Question") 
                        select new CustomXmlExpandoObject () {Id=Guid.Parse(c.Element("Id").Value)}.BString("Category",  c.Element("Category")).BString("Question", c.Element("Question"))).ToList() ;
            return query;            
        }

        public void SelectQuestion(Guid QuestionId)
        {            
            try
            {
                UpdateExamInformation();
                this.SessionService.DesignQuestionId = QuestionId;
                this.NavigationService.NavigateRoute(Constants.RoutesNames.DesignQuestion);
            }
            catch (Exception ex)
            {
                bool Rethrow = ExceptionPolicy.HandleException(ex, Infrastructure.Aspect.ExceptionHandling.ExceptionPolicyNames.WebPresenterPolicy);
                if (Rethrow)
                    throw;
            }
        }

        public void BackToExams()
        {
            try
            {
                UpdateExamInformation();
                this.SessionService.DesignExamId = null;
                this.NavigationService.NavigateRoute(Constants.RoutesNames.DesigMgmExams);
            }
            catch (Exception ex)
            {
                bool Rethrow = ExceptionPolicy.HandleException(ex, Infrastructure.Aspect.ExceptionHandling.ExceptionPolicyNames.WebPresenterPolicy);
                if (Rethrow)
                    throw;
            }            
        }
    }
}
